package org.jugile.util;

/*

Copyright (C) 2007-2011 Jukka Rahkonen  email: jukka.rahkonen@iki.fi

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

*/

import java.util.HashMap;
import java.util.Map;

import org.jugile.util.Jugile;

/**
 * "Again, the kingdom of heaven is like unto treasure hid in a field; 
 *  the which when a man hath found, he hideth, and for joy thereof goeth 
 *  and selleth all that he hath, and buyeth that field.
 *  Again, the kingdom of heaven is like unto a merchant man, seeking goodly pearls:
 *  Who, when he had found one pearl of great price, went and sold all that he had, 
 *  and bought it." (Math 13:44-46)
 *  
 * ==========
 *  
 * Simple cache implementation for application object caching needs.
 * @author jukka.rahkonen@iki.fi
 */
public class CacheProto extends Jugile implements Cache {

	private class Item {
		public Object o;
		public long expires;
		public Item(Object o, int secs) {
			this.o = o;
			expires = System.currentTimeMillis() + secs*1000L;
		}
		public boolean isValid() {
			return expires > System.currentTimeMillis();
		}
	}
	
	private Map<String,Item> map = new HashMap<String,Item>();
	
	public void flush() {
		map = new HashMap<String,Item>();
	}

	public Object flush(String key) {
		Item i = map.remove(key);
		if (i == null) return null;
		if (!i.isValid()) return null;
		return i.o;
	}

	public Object get(String key) {
		Item i = map.get(key);
		if (i == null) return null;
		if (!i.isValid()) return null;
		return i.o;
	}

	public void set(String key, Object o) {
		set(key,o,60);
	}

	public void set(String key, Object o, int secs) {
		Item i = new Item(o, secs);
		map.put(key, i);		
	}

}
